package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.cache.util.RedisKeys;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import cn.wolfcode.luowowo.website.annotation.LoginRequire;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class LoginController {

    @Reference
    private IUserInfoService userInfoService;

    @LoginRequire
    @RequestMapping("/hello")
    @ResponseBody
    public Object hello(Long id) {
        System.out.println("id："+id);
        return userInfoService.get(id);
    }

    //手机号唯一性检查
    @RequestMapping("/checkPhone")
    @ResponseBody
    public Object checkPhone(String phone){
        return userInfoService.checkPhone(phone);
    }

    //短信验证码的发送
    @RequestMapping("/sendVerifyCode")
    @ResponseBody
    public Object sendVerifyCode(String phone){
        userInfoService.sendVerifyCode(phone);
        return AjaxResult.SUCCESS;
    }

    //用户注册
    @RequestMapping("/userRegist")
    @ResponseBody
    public Object userRegist(String phone, String nickname,String password,String rpassword,String verifyCode){
        userInfoService.userRegist(phone,nickname,password,rpassword,verifyCode);
        return AjaxResult.SUCCESS;
    }

    //用户登录
    @RequestMapping("/userLogin")
    @ResponseBody
    public Object userLogin(HttpServletRequest request, HttpServletResponse response, String username, String password){
        //查询用户信息，生成token将用户信息存放到redis中并将token返回用于存储到cookie，如果账号密码不匹配则执行自定义异常
        String token = userInfoService.selectUserByUsernameAndPassword(username, password);
        //创建cookie将token名作为name token值作为值添加到cookies中，并设置有效时间30分钟 然后通过response对象响应给前端
        CookieUtil.setCookie("token", token,RedisKeys.USER_LOGIN_TOKEN.getTime().intValue(),response);
        return new AjaxResult(true,"登录成功");
    }

}
